package com.example.java_chatroom1.controller;

import com.example.java_chatroom1.model.Friend;
import com.example.java_chatroom1.model.MessageSession;
import com.example.java_chatroom1.model.Result;
import com.example.java_chatroom1.model.User;
import com.example.java_chatroom1.server.MessageInfoService;
import com.example.java_chatroom1.server.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/message")
public class MessageSessionController {
    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageInfoService messageInfoService;

    @RequestMapping("/getSessionList")
    public Result<List<MessageSession>> getSessionList(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        int userId = user.getUserId();
        List<Integer> sessionIds = messageService.getSessionIdByUserId(userId);
        List<MessageSession> ret = new ArrayList<>();
        for (Integer n : sessionIds) {
            List<Friend> friends = messageService.getFriendBySessionId(n,userId);
            MessageSession messageSession = new MessageSession();
            messageSession.setSessionId(n);
            messageSession.setFriends(friends);
            String lastTime = messageInfoService.getLastMessageBySessionId(n);
            if (lastTime == null) lastTime = "";
            messageSession.setLastTime(lastTime);
            ret.add(messageSession);
        }
        return Result.success(ret);
    }

    //需要保证这些操作具有原子性，所以需要使用事务
    @Transactional
    @RequestMapping("/createSession")
    public Result<Integer> createSession(Integer friendId,HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        int userId = user.getUserId();
        MessageSession messageSession = new MessageSession();
        int ret = messageService.addIntoMessageSession(messageSession);
        if (ret < 0) {
            return  Result.fail(500,-1,"创建会话失败，请联系管理员！");
        }
        ret = messageService.addIntoMessageSessionUser(messageSession.getSessionId(), userId);
        if (ret < 0) {
            return  Result.fail(500,-1,"创建会话失败，请联系管理员！");
        }
        ret = messageService.addIntoMessageSessionUser(messageSession.getSessionId(), friendId);
        if (ret < 0) {
            return  Result.fail(500,-1,"创建会话失败，请联系管理员！");
        }
        return Result.success(messageSession.getSessionId());
    }
}
